package icom.acm.action;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class DoAction extends ActionSupport implements ServletRequestAware,SessionAware,ServletResponseAware  {
	private HttpServletRequest request;	
	private HttpServletResponse response;
	private HttpSession session;
	private Map sessionMap;	
	
	public void getVerification(){
		String ver = (String)session.getAttribute("verification");		
		try {
			PrintWriter out = response.getWriter();
			out.append(ver);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public void verification(){
		response.setContentType("image/jpeg; charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Pragma","No-cache"); 
		response.setHeader("Cache-Control","no-cache"); 
		response.setDateHeader("Expires", 0); 
		int width;
		int height;
		int size;
		try{
		width = Integer.parseInt(request.getParameter("width"));
		height = Integer.parseInt(request.getParameter("height"));
		size = Integer.parseInt(request.getParameter("size"));
		} catch(Exception ex){
			width = 60;height = 20;
			size = 5120;
		}
		icom.acm.util.Verificatio ver = new icom.acm.util.Verificatio(width, height);
		ver.build();		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		session.setAttribute("verification", ver.getSRand());
		OutputStream output = null;
		BufferedOutputStream bos = null;
		try {
			ImageIO.write(ver.getImage(), "JPEG",baos);
			byte[] bs = new byte[size];
			bs = baos.toByteArray();
			output=response.getOutputStream();
			bos = new BufferedOutputStream(output);
			bos.write(bs);
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			try {
				bos.flush();
				output.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	@Override
	public void setServletRequest(HttpServletRequest arg) {
		request = arg;
		session = request.getSession();
	}
	@Override
	public void setSession(Map<String, Object> arg) {
		sessionMap = arg;
	}
	@Override
	public void setServletResponse(HttpServletResponse arg) {
		response = arg;		
	}
}
